using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;
using System.Text;

namespace BlazeApps.Library.Comments
{
    [Serializable()]
    public class Comment : Csla.BusinessBase<Comment>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _id = Guid.NewGuid();
        private Guid _parentid = Guid.Empty;
        private Guid _itemid = Guid.NewGuid();
        private Guid _userid = Guid.NewGuid();
        private string _subject = string.Empty;
        private string _comments = string.Empty;
        private SmartDate _createdate = new SmartDate(DateTime.Now);

        [System.ComponentModel.DataObjectField(true, true)]
        public Guid id
        {
            get
            {
                CanReadProperty("id", true);
                return _id;
            }
        }

        public Guid parentid
        {
            get
            {
                CanReadProperty("parentid", true);
                return _parentid;
            }
            set
            {
                CanWriteProperty("parentid", true);
                if (!_parentid.Equals(value))
                {
                    _parentid = value;
                    PropertyHasChanged("parentid");
                }
            }
        }

        public Guid itemid
        {
            get
            {
                CanReadProperty("itemid", true);
                return _itemid;
            }
            set
            {
                CanWriteProperty("itemid", true);
                if (!_itemid.Equals(value))
                {
                    _itemid = value;
                    PropertyHasChanged("itemid");
                }
            }
        }

        public Guid userid
        {
            get
            {
                CanReadProperty("userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("userid");
                }
            }
        }

        public string subject
        {
            get
            {
                CanReadProperty("subject", true);
                return _subject;
            }
            set
            {
                CanWriteProperty("subject", true);
                if (value == null)
                    value = string.Empty;
                if (!_subject.Equals(value))
                {
                    _subject = value;
                    PropertyHasChanged("subject");
                }
            }
        }

        public string comments
        {
            get
            {
                CanReadProperty("comments", true);
                return _comments;
            }
            set
            {
                CanWriteProperty("comments", true);
                if (value == null)
                    value = string.Empty;
                if (!_comments.Equals(value))
                {
                    _comments = value;
                    PropertyHasChanged("comments");
                }
            }
        }

        public DateTime createdate
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Date;
            }
        }

        public string createdateString
        {
            get
            {
                CanReadProperty("createdate", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("createdate", true);
                if (value == null)
                    value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("createdate");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _id;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            ////
            //// userid
            ////
            //ValidationRules.AddRule(CommonRules.StringMaxLength, new CommonRules.MaxLengthRuleArgs("userid", 2000));
            ////
            //// comments
            ////
            //ValidationRules.AddRule(CommonRules.StringRequired, "comments");
            ////
            //// createdate
            ////
            //ValidationRules.AddRule(CommonRules.StringRequired, "createdateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in Comment
            //AuthorizationRules.AllowRead("id", "CommentReadGroup");
            //AuthorizationRules.AllowRead("itemid", "CommentReadGroup");
            //AuthorizationRules.AllowRead("userid", "CommentReadGroup");
            //AuthorizationRules.AllowRead("IvAccesstype", "CommentReadGroup");
            //AuthorizationRules.AllowRead("comments", "CommentReadGroup");
            //AuthorizationRules.AllowRead("createdate", "CommentReadGroup");

            //AuthorizationRules.AllowWrite("userid", "CommentWriteGroup");
            //AuthorizationRules.AllowWrite("IvAccesstype", "CommentWriteGroup");
            //AuthorizationRules.AllowWrite("comments", "CommentWriteGroup");
            //AuthorizationRules.AllowWrite("createdate", "CommentWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in Comment
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("CommentViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in Comment
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("CommentAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in Comment
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("CommentEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in Comment
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("CommentDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private Comment()
        { /* require use of factory method */
        }

        public static Comment NewComment()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Comment");
            return DataPortal.Create<Comment>();
        }

        public static Comment GetComment(Guid id)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a Comment");
            return DataPortal.Fetch<Comment>(new Criteria(id));
        }

        public static void DeleteComment(Guid id)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Comment");
            DataPortal.Delete(new Criteria(id));
        }

        public override Comment Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a Comment");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a Comment");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a Comment");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid id;

            public Criteria(Guid id)
            {
                this.id = id;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@commentid", criteria.id);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetCommentsByItemID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _id = dr.GetGuid("id");
            _itemid = dr.GetGuid("itemid");
            _userid = dr.GetGuid("userid");
            _subject = dr.GetString("subject");
            _comments = dr.GetString("comments");
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertComment.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {

            DAL.AddParameter("@id", _id);
            DAL.AddParameter("@itemid", _itemid);

            if (_userid != Guid.Empty)
                DAL.AddParameter("@userid", _userid);
            else
                DAL.AddParameter("@userid", DBNull.Value);

            if (_parentid != Guid.Empty)
                DAL.AddParameter("@parentid", _parentid);
            else
                DAL.AddParameter("@parentid", DBNull.Value);

            DAL.AddParameter("@subject", _subject);
            DAL.AddParameter("@comments", _comments);
            //cm.Parameters["@Newid"].Direction = ParameterDirection.Output;
            //cm.Parameters["@Newitemid"].Direction = ParameterDirection.Output;
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        //protected override void DataPortal_Update()
        //{
        //    if (base.IsDirty)
        //    {
        //        ExecuteUpdate();
        //    }
        //}

        //private void ExecuteUpdate()
        //{
        //    DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

        //    AddUpdateParameters(ref DAL);

        //    DAL.ExecuteNonQuery("usp_update_page", CommandType.StoredProcedure, ConnectionState.Open);
        //}

        //private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        //{
        //    DAL.AddParameter("@id", _id);
        //    DAL.AddParameter("@itemid", _itemid);
        //    if (_userid != string.Empty)
        //        DAL.AddParameter("@userid", _userid);
        //    else
        //        DAL.AddParameter("@userid", DBNull.Value);
        //    DAL.AddParameter("@iv_accesstype", _ivAccesstype);
        //    DAL.AddParameter("@comments", _comments);
        //}

        //private void UpdateChildren(SqlConnection cn)
        //{
        //}
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_id));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteComment.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@commentid", criteria.id);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
